<?php

/**
 * 页面跳转
 * 
 * @param $url
 */
function go($url) {
	header ( 'location:' . $url );
	exit ();
}

/**
 * 获得现在时间（例：2010-01-30 12:30:20）
 * 
 */
function getNowTime() {
	return date ( 'Y-m-d H:i:s' );
}

//保存网页
function page_save($FILE, $base_url) {
	
	//允许上传类型
	$allowpictype = array ('csv' ,'xls');
	
	//检查
	$FILE ['size'] = intval ( $FILE ['size'] );
	if (empty ( $FILE ['size'] ) || empty ( $FILE ['tmp_name'] ) || ! empty ( $FILE ['error'] )) {
		return 'false@@unknow_upload_file_size';
	}
	
	//判断后缀
	$fileext = fileext ( $FILE ['name'] );
	if (! in_array ( $fileext, $allowpictype )) {
		return 'false@@only_allows_upload_file_types';
	}
	
	//获取目录
	if (! $filepath = getfilepath ( $fileext, true, $base_url )) {
		return 'false@@unable_to_create_upload_directory_server';
	}
	
	//本地上传
	$new_name = $filepath;
	$tmp_name = $FILE ['tmp_name'];
	if (@copy ( $tmp_name, $new_name )) {
		@unlink ( $tmp_name );
	} elseif ((function_exists ( 'move_uploaded_file' ) && @move_uploaded_file ( $tmp_name, $new_name ))) {
	} elseif (@rename ( $tmp_name, $new_name )) {
	} else {
		return 'false@@mobile_picture_temporary_failure';
	}
	
	if($fileext=='xls'){
		$convert = F_LIB.'xls2csv.pl';
		$csvName = str_replace('.xls', '.csv', $new_name);
		exec("$convert $new_name $csvName 1");
		$new_name = $csvName;
	}
	
	//是否压缩
	//获取上传后图片大小
	if (@$newfilesize = filesize ( $new_name )) {
		$FILE ['size'] = $newfilesize;
	}
	
	return 'true@@' . $new_name;
}

//获取上传路径
function getfilepath($fileext, $mkdir = false, $path) {
	
	$filepath = date ( 'YmdHis' ) . '_' . random ( 4 ) . ".$fileext";
	$name1 = date ( 'Ym' );
	$name2 = date ( 'd' );
	
	/*if ($mkdir) {
		$newfilename = $path . './' . $name1;
		if (! is_dir ( $newfilename )) {
			if (! @mkdir ( $newfilename )) {
				return $filepath;
			}
		}
		$newfilename .= '/' . $name2;
		if (! is_dir ( $newfilename )) {
			if (! @mkdir ( $newfilename )) {
				return $name1 . '/' . $filepath;
			}
		}
	}*/
// 	return $path . '/' . $name1 . '/' . $name2 . '/' . $filepath;
	return $path . $filepath;
}

//获取文件名后缀
function fileext($filename) {
	return strtolower ( trim ( substr ( strrchr ( $filename, '.' ), 1 ) ) );
}

//产生随机字符
function random($length, $numeric = 0) {
	PHP_VERSION < '4.2.0' ? mt_srand ( ( double ) microtime () * 1000000 ) : mt_srand ();
	$seed = base_convert ( md5 ( print_r ( $_SERVER, 1 ) . microtime () ), 16, $numeric ? 10 : 35 );
	$seed = $numeric ? (str_replace ( '0', '', $seed ) . '012340567890') : ($seed . 'zZ' . strtoupper ( $seed ));
	$hash = '';
	$max = strlen ( $seed ) - 1;
	for($i = 0; $i < $length; $i ++) {
		$hash .= $seed [mt_rand ( 0, $max )];
	}
	return $hash;
}

/**
 * 获得Html保存路径
 * 
 * @param $newsNum
 */
function getHtmlUrl($newsNum){
	
	$filepath = $newsNum.".html";
	$name1 = date ( 'Ym' );
	$name2 = date ( 'd' );
	
	$newfilename = HtmlUrl .'/'. $name1;
	if(! is_dir(HtmlUrl)){
		if(!@mkdir(HtmlUrl)){
			return $filepath;
		}
	}
	if (! is_dir ( $newfilename )) {
		if (! @mkdir ( $newfilename )) {
			echo "file:$newfilename<br />";
			return $filepath;
		}
	}
	$newfilename .= '/' . $name2;
	if (! is_dir ( $newfilename )) {
		if (! @mkdir ( $newfilename )) {
			return $name1 . '/' . $filepath;
		}
	}
	
	return HtmlUrl . '/' . $name1 . '/' . $name2 . '/' . $filepath;
}

//分页
function pageCount($total, $pageIndex, $url){
	
	$next_page='下一页';
    $pre_page='上一页';
    $first_page='首页';
    $last_page='尾页';	
	
	if($total%PageNum==0){
		$pageNumber = intval($total/PageNum);
	}else{
		$pageNumber = intval($total/PageNum)+1;
	}

	$html = '';
	
	if($pageNumber<1){
		return $html;
	}
	
	$next_number = $pageIndex+1>$pageNumber?'':$pageIndex+1;
	$pre_number = $pageIndex-1==0?'':$pageIndex-1;
	
	//导向键
	$a_first_page = $pageIndex==1?'':"<a href='$url&pageIndex=1'  title='First Page'>$first_page</a>";
	$a_last_page = $pageIndex==$pageNumber?'':"<a href='$url&pageIndex=$pageNumber' title='Last Page' >$last_page</a>";
	$a_next_page = $next_number==''?'':"<a href='$url&pageIndex=$next_number' title='Next Page'  >$next_page</a>";
	$a_pre_page = $pre_number==''?'':"<a href='$url&pageIndex=$pre_number' title='Previous Page' >$pre_page</a>";
	
	/*
	//下拉框
	$select_html = "<select id='selectUrl' onchange=selectChangeUrl('selectUrl','".$url."'); >";
	for($index=1;$index<$pageNumber+1;$index++){
		if($index==$pageIndex){
			$select_html .= "<option value='$index' selected=true >$index</option>";
		}else{
			$select_html .= "<option value='$index'>$index</option>";
		}
	}
	$select_html .= "</select>";
	*/
	
	$currentPage = "<a href='#'>".$pageIndex."</a>";
	
	//整合
	$html = $a_first_page.'&nbsp;'.$a_pre_page.'&nbsp;'.$currentPage.'&nbsp'.$a_next_page.'&nbsp;'.$a_last_page.'&nbsp;';
	
	return $html;
}

function AjaxPageCount($total, $pageIndex, $url){
	
	$next_page='下一页';
    $pre_page='上一页';
    $first_page='首页';
    $last_page='尾页';	
	
	if($total%PageNum==0){
		$pageNumber = intval($total/PageNum);
	}else{
		$pageNumber = intval($total/PageNum)+1;
	}

	$html = '';
	
	if($pageNumber<=1){
		return $html;
	}
	
	$url = host.$url;
	
	$next_number = $pageIndex+1>$pageNumber?'':$pageIndex+1;
	$pre_number = $pageIndex-1==0?'':$pageIndex-1;
	
	//导向键
	$a_first_page = $pageIndex==1?'':'<a onclick="ajaxPage(\''.$url.'\',1);" >'.$first_page.'</a>';
	$a_last_page = $pageIndex==$pageNumber?'':'<a onclick="ajaxPage(\''.$url.'\',\''.$pageNumber.'\');" >'.$last_page.'</a>';
	$a_next_page = $next_number==''?'':'<a onclick="ajaxPage(\''.$url.'\',\''.$next_number.'\');" >'.$next_page.'</a>';
	$a_pre_page = $pre_number==''?'':'<a onclick="ajaxPage(\''.$url.'\',\''.$pre_number.'\');" >'.$pre_page.'</a>';
	
	//下拉框
	$select_html = "<select id='selectUrl' onchange=ajaxSelectChangeUrl('selectUrl','".$url."'); >";
	for($index=1;$index<$pageNumber+1;$index++){
		if($index==$pageIndex){
			$select_html .= "<option value='$index' selected=true >$index</option>";
		}else{
			$select_html .= "<option value='$index'>$index</option>";
		}
	}
	$select_html .= "</select>";
	
	$html = '<div style="text-align:center;padding-top: 20px;">';
	
	//整合
	$html .= $a_first_page.'&nbsp;'.$a_pre_page.'&nbsp;'.$a_next_page.'&nbsp;'.$a_last_page.'&nbsp;'.$select_html;
	
	$html .= '</div>';
	
	return $html;
}

function get_user_ip()
{
	if ($HTTP_SERVER_VARS["HTTP_CLIENT_IP"]) {
		$IpIn = $HTTP_SERVER_VARS["HTTP_CLIENT_IP"];
	} elseif ($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"]) {
		$IpIn = $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"];
	} elseif ($HTTP_SERVER_VARS["REMOTE_ADDR"]) {
		$IpIn = $HTTP_SERVER_VARS["REMOTE_ADDR"];
	} elseif (getenv("HTTP_CLIENT_IP")) {
		$IpIn = getenv("HTTP_CLIENT_IP");
	} elseif (getenv("HTTP_X_FORWARDED_FOR")) {
		$IpIn = getenv("HTTP_X_FORWARDED_FOR");
	} elseif (getenv("REMOTE_ADDR")) {
		$IpIn = getenv("REMOTE_ADDR");
	} else {
		$IpIn = "67.202.25.211";
	}
	//$IpIn = "24.131.207.228";
	return $IpIn;
}

function getPostStringParam($str){
	return addslashes($_POST[trim($str)]);
}

function getPostDateParam($str){
	$str = getPostStringParam($str);
	return date('Y-m-d H:i:s',strtotime($str));
}

function getPostIntParam($str){
	$int = intval(getPostStringParam($str));
	$int <= 0 ? 0:$int;
	return $int;
}

function getGetStringParam($str){
	return addslashes($_GET[trim($str)]);
}

function getGetIntParam($str){
	$int = intval(getGetStringParam($str));
	$int <= 0 ? 0:$int;
	return $int;
}

function getCheckBoxParam($str){
	if(intval($str)==1){
		return 1;
	}else{
		return 0;
	}
}

function formatCsvDate($str){
	$strArr = explode(' ', $str);
	if($strArr[1]=='24-00-00'){
		return $strArr[0].' 23:59:59';
	}
	$str_re=str_replace('-', ':', $strArr[1]);
	return $strArr[0].' '.$str_re;
}

function formatToUTF8($str){
// 	return mb_convert_encoding($str, "UTF-8", "GBK");
	return $str;
}

function formatToGBK($str){
	return mb_convert_encoding($str, "GBK", "UTF-8");
}

function ckLogin() {
	$SpecialModel = array('launch', 'pic');
	$SpecialAction = array('getKeywordsAds', 'getVBCAds', 'getKWHTML', 'getPicAds', 'getPicAdsHTML');
	if (isset($_GET['do'])) {
		$do = explode('.', $_GET['do']);
	} else {
		$do = explode('.', DEFAULT_DO);
	}
	if (in_array($do[0], $SpecialModel) && in_array($do[1], $SpecialAction)){
		return true;
	}elseif ($do[0] == 'login') {
		return true;
	} elseif ($_SESSION['ads']['loginAllowed'] == 1) {
		return true;
	} else {
		return false;
	}
}

function getAdsTypeByName($name){
	$nameArr = explode('_', $name);
	$type = 'vbc';
	
	if(is_array($nameArr)){
		if($nameArr[1]=='KW'){
			$type = 'keywords';
		}		
	}
	return $type;
}

//转换json中汉字类型
function js_unescape($str){
	$ret = '';
	$len = strlen($str);
	for ($i = 0; $i < $len; $i++)
	{
		if ($str[$i] == '\\' && $str[$i+1] == 'u')
		{
			$val = hexdec(substr($str, $i+2, 4));
			if ($val < 0x7f) $ret .= chr($val);
			else if($val < 0x800) $ret .= chr(0xc0|($val>>6)).chr(0x80|($val&0x3f));
			else $ret .= chr(0xe0|($val>>12)).chr(0x80|(($val>>6)&0x3f)).chr(0x80|($val&0x3f));
			$i += 5;
		}else{
			$ret .= $str[$i];
		}
	}
	return $ret;
}

/**
 * http://cmstop.viivtech.com/myrss.php?skip=0&pagesize=10
 *
 * @param String $url (http://cmstop.viivtech.com/myrss.php)
 * @param int $skip
 * @param int $pagesize
 * @return Array
 */
function readRSS($url, $skip, $pagesize){
	
	$url = $url.'?skip='.$skip.'&pagesize='.$pagesize;

	$curl = curl_init($url);
	curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
	$resultRSS = curl_exec($curl);
	curl_close($curl);
	
	libxml_use_internal_errors(true);
	$xmlObj = simplexml_load_string($resultRSS);
	$xmlObj = (array)$xmlObj;
	$RSSAry = array();
	
	if (!$xmlObj) {
		return $RSSAry['error1'];
	}
	libxml_use_internal_errors(false);
	
	$items = $xmlObj['channel'];
	
	$index = 0;
	foreach ($items as $item){
		$RSSAry[$index]['id'] = intval($item->id);
// 		$RSSAry[$index]['title'] = formatToGBK(strval($item->title));
// 		$RSSAry[$index]['content'] = formatToGBK(strval($item->content));
// 		$RSSAry[$index]['category'] = formatToGBK(strval($item->category));
// 		$RSSAry[$index]['tags'] = formatToGBK(strval($item->tags));
		$RSSAry[$index]['title'] = strval($item->title);
		$RSSAry[$index]['content'] = strval($item->content);
		$RSSAry[$index]['category'] = strval($item->category);
		$RSSAry[$index]['tags'] = strval($item->tags);
		$RSSAry[$index]['modified'] = strval($item->modified);
		$RSSAry[$index]['pv'] = intval($item->pv);
		
		$index++;
	}
	
	return $RSSAry;
}

function readElleRSS($catID, $skip){
	$url = 'http://app.ellechina.com/?app=rss&controller=index&action=feed';

	$url = $url.'&skip='.$skip;
	
	if($catID!=''){
		$url = $url.'&catid='.$catID;
	}
	
	$curl = curl_init($url);
	curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
	$resultRSS = curl_exec($curl);
	curl_close($curl);
	
	$xmlObj = simplexml_load_string($resultRSS);
	$RSSAry = array();
	
	if (!$xmlObj) {
		return $RSSAry['error1'];
	}
	libxml_use_internal_errors(false);
	
	$items = $xmlObj->channel->item;
	
	$index = 0;
	foreach ($items as $item){
		$RSSAry[$index]['id'] = addslashes(intval($item->contentid));
		$RSSAry[$index]['title'] = addslashes(strval($item->title));
		$RSSAry[$index]['link'] = addslashes(strval($item->link));
		$RSSAry[$index]['channel'] = addslashes(strval($item->channel));
		$RSSAry[$index]['category'] = addslashes(strval($item->category));
		$RSSAry[$index]['content'] = addslashes(strval($item->description));
		$RSSAry[$index]['tags'] = addslashes(strval($item->tags));
		$RSSAry[$index]['pubDate'] = date('Y-m-d H:i:s', strtotime(strval($item->pubDate)));
		$RSSAry[$index]['modified'] = date('Y-m-d H:i:s', strtotime(strval($item->modDate)));
		$RSSAry[$index]['pv'] = addslashes(intval($item->pv));
		$RSSAry[$index]['brand'] = addslashes(strval($item->brand));
	
		$index++;
	}
	
	return $RSSAry;
}

function readElleRSS_pic($catID, $skip){
	
	$url = 'http://app.ellechina.com/?app=rss&controller=index&action=feed';
	
	$url = $url.'&skip='.$skip;
	
	if($catID!=''){
		$url = $url.'&catid='.$catID;
	}
	
	$curl = curl_init($url);
	curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
	$resultRSS = curl_exec($curl);
	curl_close($curl);
	
	$xmlObj = simplexml_load_string($resultRSS);
	$RSSAry = array();
	
	if (!$xmlObj) {
		return $RSSAry['error1'];
	}
	libxml_use_internal_errors(false);
	
	$items = $xmlObj->channel->item;
	
	$additionArr = array();
	$channelArr = array();
	$classArr = array();
	$brandArr = array();
	$tagArr = array();
	
	$index = 0;
	foreach ($items as $item){
		$contentid = addslashes(intval($item->contentid));
		$imageArr = $item->images->image;
		foreach ($imageArr as $imageInfo) {
			$RSSAry[$index]['pic_src'] = addslashes(strval($imageInfo->src));
			$RSSAry[$index]['channel'] = addslashes(strval($imageInfo->channel));
			$RSSAry[$index]['class'] = addslashes(strval($imageInfo->class));
			$RSSAry[$index]['brand'] = addslashes(strval($imageInfo->brand));
			$RSSAry[$index]['tag'] = addslashes(strval($imageInfo->tags));
			$RSSAry[$index]['url'] = addslashes(strval($imageInfo->url));
			$RSSAry[$index]['link'] = addslashes(strval($item->link));
			$RSSAry[$index]['contentid'] = $contentid;
			$RSSAry[$index]['createTime'] = getNowTime();
			$RSSAry[$index]['modified'] = getNowTime();
			$channelArr[] = addslashes(strval($imageInfo->channel));
			$classArr[] = addslashes(strval($imageInfo->class));
			$brandArr[] = addslashes(strval($imageInfo->brand));
			$tagArr[] = addslashes(strval($imageInfo->tags));
			$index++;
		}
	}
	
	if(is_array($channelArr))
		$additionArr['channel'] = array_unique($channelArr);
	if(is_array($classArr))
		$additionArr['class'] = array_unique($classArr);
	if(is_array($brandArr))
		$additionArr['brand'] = array_unique($brandArr);
	if(is_array($tagArr))
		$additionArr['tag'] = array_unique($tagArr);
	
	$returnArr = array(
		'rss' => $RSSAry,
		'addition' => $additionArr,
	);
	
	return $returnArr;
}

/*
 * $url = 'http://d.11b.us/baiduapi/';
 * 
 */
function readBaiduKeywords($url, $keywords, $limit){
	
	$url = $url.'?kw='.$keywords.'&limit='.$limit.'&mt=3&ot=xml';
	
	$curl = curl_init($url);
	curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
	$result = curl_exec($curl);
	curl_close($curl);
	
	libxml_use_internal_errors(true);
	$xmlObj = simplexml_load_string($result);
	$xmlObj = (array)$xmlObj;
	
	$baiduKeywords = array();
	
	$items = $xmlObj['response'];
	$index = 0;
	foreach ($items as $item){
		if(empty($item->kw))continue;
		$baiduKeywords[$index]['kw'] = strval($item->kw);
		$baiduKeywords[$index]['pv'] = strval($item->pv);
		
		$index++;
	}
	
	return $baiduKeywords;
}

/*
 * $url = 'http://124.232.163.48:8080/solr/db/select/'
 */
function searchBySolr($url, $keywords){
	
	$url = $url.'?rows=1000&q='.urlencode($keywords);
	
	$curl = curl_init($url);
	curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
	$result = curl_exec($curl);
	curl_close($curl);
	
	libxml_use_internal_errors(true);
	$xmlObj = simplexml_load_string($result);
	$xmlObj = (array)$xmlObj;
	
	$solrArr = array();
	
	$items = $xmlObj['result'];
	
	if($_GET['debug_searchsolr']==1){
		echo $url.'<br>';
		echo '<pre>';
		print_r($items);
	}
	
	$index = 0;
	if(count($items)>0){
		foreach ($items as $item){
			if(empty($item->str[1]))continue;
			$solrArr[$index] = strval($item->str[1]);
		
			$index++;
		}
	}
	return $solrArr;
}

/*
 * $url = 'http://124.232.163.48:8080/solr/db/select/'
*/
function searchArticlesFromSolrByKW($url, $keywords){

	$url = $url.'?rows=1000&q='.urlencode($keywords);

	$curl = curl_init($url);
	curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
	$result = curl_exec($curl);
	curl_close($curl);

	libxml_use_internal_errors(true);
	$xmlObj = simplexml_load_string($result);
	$xmlObj = (array)$xmlObj;
	
	$articleArr = array();

	$items = $xmlObj['result'];
	$index = 0;
	foreach ($items as $item){
		if(empty($item->str[1]))continue;
		$articleArr[$index]['id'] = strval($item->str[1]);
		$articleArr[$index]['content'] = strval($item->str[0]);
		$articleArr[$index]['pv'] = intval($item->str[3]);
		$articleArr[$index]['tags'] = strval($item->str[4]);
		$articleArr[$index]['title'] = strval($item->str[5]);
		$articleArr[$index]['link'] = strval($item->str[2]);

		$index++;
	}
	return $articleArr;
}

function checkCallBack($callback, $array){
	if(empty($callback) || $callback==''){
		return $array;
	}else{
		return $callback.'('.$array.');';
	}
}

function checkFilename($filename, $base_url){
	
	if(empty($filename) || $filename=='')return false;
	
	$new_name = $base_url.$filename;
	
	$ext = fileext($filename);
	if($ext=='xls'){
		$convert = F_LIB.'xls2csv.pl';
		$csvName = str_replace('.xls', '.csv', $new_name);
		exec("$convert $new_name $csvName 1");
		$filename = str_replace('.xls', '.csv', $filename);
	}
	
	return $filename;
}

function findAdsPositionByUrl($launchID, $adsID){
	$positionArr = include F_CONF.'position.config.php';
	
	$position = "";
	foreach ($positionArr as $key=>$value) {
		$url = "http://hfm.adsame.com/s?z=hfm&c=$value&l=$launchID&b=$adsID";
		$content = file_get_contents($url);		
		
		if(stripos($content, "http://hfm.adsame.com/")!==false){
			$position = $key;
			break;
		}
	}
	return $position;
}

function setLog ($msg) {
	$url = isset($_SERVER) ? ' Url: '.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] : '';
	error_log('  '.$msg.'.'.$url);
}

function isHDID($id){
	if(stripos($id, 'HD')===false){
		return false;
	}else{
		return true;
	}
}

function replaceForScript($str){
	return str_replace("'", '\'',str_replace("\\", "\\\\", $str));
}

function checkVaildDate($begin, $end){
	$now = date('Y-m-d H:i:s');
	if($begin<=$now && $now<=$end)return true;
	return false;
}

?>